'''
Created on 2012-8-27

@author: null
'''
from flask import redirect, url_for, jsonify
from flask.globals import session, request
from functools import wraps
from services import UserService

def requires_sign_in(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if session.get("signed_in", None) != True:
            return redirect(url_for("user.sign_in", next=request.url)); 
        
        return f(*args, **kwargs)

    return decorated

def permission_denied(message="Access denied."):
    data = {'status': "ACCESS_DENIED", 'message': message}
    resp = jsonify(data)

    resp.status_code = 401
    resp.headers['WWW-Authenticate'] = 'Basic realm="Service"'

    return resp

def secure_api(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        session["signed_in"] = False;
        auth = request.authorization;
        authorized = False;
        
        if not auth: 
            return permission_denied();
        else:
            userService = UserService();
            authorized = userService.check_auth(auth.username, auth.password);
            if not authorized:
                return permission_denied("Incorrect user name or password.");
        
        if authorized:
            return f(*args, **kwargs);

    return decorated
